package se.ytterman.jpcap.data.ethernet;

import java.lang.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;

import se.ytterman.jpcap.data.bytearray.ArrayBinaryData;

public class MACAddress extends ArrayBinaryData {

    public MACAddress(byte[] byte_buffer) throws Exception {
	super(byte_buffer);

	if(byte_buffer.length != 6) {
	    throw new Exception("");
	}
    }

    public MACAddress(InputStream packetInputStream) throws Exception {
	super(6, packetInputStream);
    }

    public MACAddress(String mac_address) throws Exception {
	super(6);

	String mac_pattern = "([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2}):" +
	    "([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2}):" +
	    "([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2})";

	Pattern p = Pattern.compile(mac_pattern);
	Matcher m = p.matcher(mac_address);

	// Perform basic check of format
	if(m.matches()) {
	    // Iterate and print...
	    for(int i = 1; i <= m.groupCount(); i++) {
		// Extract "byte" value for each part of the MAC address
		int byte_value = Integer.parseInt(m.group(i), 16);
		
		this.byte_buffer[i-1] = (byte)byte_value;
	    }
	}
	else {
	    // XXX Throw exception
	}
    }    

    // toString
    public String toString() {
	String mac_str = String.format("%02X:%02X:%02X:%02X:%02X:%02X",
				       this.byte_buffer[0],
				       this.byte_buffer[1],
				       this.byte_buffer[2],
				       this.byte_buffer[3],
				       this.byte_buffer[4],
				       this.byte_buffer[5]
				       );

	return mac_str;
    }
}
